package com.lance.answer.question_answer.tmp;

import com.google.common.base.Strings;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * http://xinjiang.ouchn.cn/mod/url/view.php?id=343895  点击专题5的PPT学习
 */
@Slf4j
public class WatchVideo1010Tmp {

    //http://www.nmg.gov.cn/mas/openapi/pages.do?method=exPlay&appKey=gov&id=5716&autoPlay=false
    //https://vod.300hu.com/4c1f7a6atransbjngwcloud1oss/5d82e52a382171174942019585/v.f30.mp4
    //http://vfx.mtime.cn/Video/2019/02/04/mp4/190204084208765161.mp4
    //https://jvod.300hu.com/vod/product/a7d50669-f57b-4da9-8cf8-43d04372cab0/0411e189a55b41cfada876041fa7fdd7.mp4?source=2&h265=h265/18799/d7d0ab77577f4ea0bcf5bc794316045a.mp4
    public static  final String JS = "var video = document.getElementsByTagName(\"video\");if(video.length>0){ video[0].src = \"https://jvod.300hu.com/vod/product/a7d50669-f57b-4da9-8cf8-43d04372cab0/0411e189a55b41cfada876041fa7fdd7.mp4?source=2&h265=h265/18799/d7d0ab77577f4ea0bcf5bc794316045a.mp4\";}";

    public static void main(String[] args) throws Exception {
        //课程名
        String subjectName = "形势与政策";
  //      String majorName = "小学教育学前教育汉语言文学工程造价计算机信息管理水利药学人力资源"; //done
        String majorName = "other";
        //并发度
        int sync = 9;
        //是否开启休眠-兼容服务器停服
        boolean open = false;

        run(subjectName.trim(),majorName.trim(),sync,open);
    }

    public static void run (String subjectName,String majorName,int sync,boolean open) throws Exception {
        //初始化日志
        Constant.initLog();
        //获取模板路径,通过流的方式获取文件可以避免被打成jar包之后无法获取文件路径的异常

        InputStream inputStream2 = Thread.currentThread().getContextClassLoader().getResourceAsStream( subjectName + "/" + "users/" + majorName  + ".user");
        List<String> users = IOUtils.readLines(inputStream2,"utf-8");

        log.info("本次刷视频 课程名称：{},专业名称：{}",subjectName,majorName);
        log.info("本次加载用户：{} 人",users.size());

        List<List<String>> group = new ArrayList<>();
        int size = users.size();
        int step = size / sync;
        if (step == 0) {
            group.add(users);
        } else {
            for (int i = 0; i < sync; i++) {
                List<String> list2 = users.subList(step * i, (i + 1) * step);
                group.add(list2);
            }
            group.add(users.subList(step * sync, users.size()));
        }

        log.info("本次程序将加载 {} 个线程同时运行",group.size());
        for (List<String> batchUser : group) {
            Constant.THREAD_POOL_BATCH.execute(() -> {
                try {
                    int i = 1;
                    log.info("线程：{} 将执行 {} 个用户视频观看任务",Thread.currentThread().getName(),batchUser.size());
                    for (String user : batchUser) {
                        String[] strs = user.split(",");
                        String userCode = strs[0];
                        String pwd;
                        if(strs[1].length()==8){
                            pwd = strs[1];
                        }else {
                            pwd = strs[1].substring(6, 14);
                            pwd = "Ouchn"+pwd;
                        }

                        long start = System.currentTimeMillis();
                        log.info("线程：{} 开始执行第：{} 个用户视频观看任务，用户名：{}",Thread.currentThread().getName(),i,userCode);
                     //   run(paths,subjectName,"d:\\ynouAutoStudy\\chromedriver.exe",userCode,pwd,open);
                        run(null,subjectName,null,userCode,pwd,open);

                        long end = System.currentTimeMillis();
                        log.info("线程：{} 第：{} 个用户视频观看任务结束,耗时：{} min,用户名：{}",Thread.currentThread().getName(),i, (end - start) / 1000 / 60,userCode);
                        log.info("线程：{} 当前用户进度：{} / {}",Thread.currentThread().getName(),i,batchUser.size());
                        i++;
                    }
                    log.info("线程：{} 任务执行完毕",Thread.currentThread().getName());


                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

        }

    }

    public static void run(List<String> urlTasks,String subjectName,String driverPath,String userName,String password,boolean open) throws Exception {
        ChromeDriver driver = Util.getDriver(driverPath);
        String url = "http://passport.ouchn.cn/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dstudentspace%26redirect_uri%3Dhttp%253A%252F%252Fstudent.ouchn.cn%252F%2523%252Fsignin-oidc%2523%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520ouchnuser%2520ouchnstudentspaceapi%2520offline_access%26state%3Dca1cb5d0270b49fdaea508b8a846c457%26nonce%3Dd257df51b0a141ac8ed35b1caf59ef4c";
        driver.get(url);
        Thread.sleep(6000);
        Util.login(driver, userName, password);
        //Util.switchToLast(driver);
        Thread.sleep(6000);
        for (WebElement we : driver.findElements(By.className("media-body"))) {
            // 找到管理学基础
            String mediaTitle = we.findElement(By.className("media-title")).getText();

            if (!mediaTitle.contains(subjectName)) {
                continue;
            }
            //点击进入学习的按钮
            WebElement studyButton = we.findElement(By.cssSelector("button[class='btn bg-primary']"));
            studyButton.click();
            //Util.switchToLast(driver);

         //   String js = "window.open(\"http://xinjiang.ouchn.cn/course/view.php?id=2660&sectionid=118818&mid=343895\");";
        //    ((JavascriptExecutor) driver).executeScript(js);

            Thread.sleep(6000);
        }

        Util.switchToLast(driver);
        for(WebElement we:driver.findElements(By.cssSelector("h3[div='content']"))){
            System.err.println("??????????"+we.getText());
        }

        for(WebElement we:driver.findElements(By.cssSelector("h3[class='sectionname']"))){
            System.err.println("??????????222"+we.getText());
            if(Strings.isNullOrEmpty(we.getText())){
                continue;
            }
            if(we.getText().contains("专题五")){
                we.click();
                Thread.sleep(2000);
                driver.get("http://xinjiang.ouchn.cn/mod/url/view.php?id=343894");
                Thread.sleep(5000);
                driver.get("http://xinjiang.ouchn.cn/mod/url/view.php?id=343895");
                Thread.sleep(5000);
                break;
            }
        }
        Thread.sleep(2000);

        driver.close();
        driver.quit();
    }

}
